package me.dongcha.reggie402.filter;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import me.dongcha.reggie402.common.BaseContext;
import me.dongcha.reggie402.common.R;
import me.dongcha.reggie402.entity.Employee;
import me.dongcha.reggie402.service.EmployeeService;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestBody;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter(filterName = "LoginCheckFilter")
public class LoginCheckFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.warn("拦截器开始工作");

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String uri = request.getRequestURI();
        log.warn("[拦截到的URI为]:" + uri);

        boolean isAuth = checkAuthUrl(uri);
        if (isAuth) {
            log.warn("[白名单内容,放行]:" + uri);
            filterChain.doFilter(request, response);
            return;
        }

        Object employee = request.getSession().getAttribute("employee");
        if (employee != null) {
            log.warn("已经登陆了,放行");

            BaseContext.setCurrentId((Long) employee);

            filterChain.doFilter(request, response);
            return;
        }

        Object userId = request.getSession().getAttribute("user");
        if (userId != null) {
            log.warn("[手机端已经登陆了,放行]:" + uri);
            BaseContext.setCurrentId((Long) userId);
            filterChain.doFilter(request, response);
            return;
        }

        R notlogin = R.error("NOTLOGIN");
        log.error("非正常访问[未登录],拒签");
        String jsonString = JSON.toJSONString(notlogin);
        response.getWriter().write(jsonString);
    }

    public boolean checkAuthUrl(String requestUri) {
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        for (String url : authUrl) {
            if (antPathMatcher.match(url, requestUri)) {
                return true;
            }
        }
        return false;
    }

    private String[] authUrl = new String[]{
            "/employee/login",
            "/backend/**",
            "/front/**",
            "/common/upload",
            "/common/download",
            "/favicon.ico",
            "/user/login",
            "/user/sendMsg",
            "/user/logout",
            "/user/loginout"
    };

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
